package com.xjk.call.python;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import org.python.core.Py;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

/**
 * @author xjk
 * @date 2024-11-12
 */
public class TestCallPython {

  public static void main(String[] args) throws IOException, InterruptedException {

    ProcessBuilder pb = new ProcessBuilder();
    String pythonCompiler = "D:\\Programs\\Python\\Python311\\python.exe";
    String pythonFile = "D:\\Desktop\\test\\main.py";
    int n = 5;
    pb.environment().put("COUNT", String.valueOf(n));
    pb.command(pythonCompiler,pythonFile);
    Process process = pb.start();
    out(process);

    process.waitFor();

//    PythonInterpreter interpreter = new PythonInterpreter();
//    interpreter.set("python.import.site", false);
//
//    interpreter.exec("def fun(a,b):\n" + "    return a+b\n");
//    PyObject pyobj = interpreter.eval("fun(1,2)");
//    Integer tojava = Py.tojava(pyobj, int.class);
//    System.out.println(tojava);


  }

  private static void out(Process process) throws IOException {
    // 获取标准输出
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
    // 获取标准错误
    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "GBK"));

    // 读取标准输出
    String s;
    System.out.println("标准输出:");
    while ((s = stdInput.readLine()) != null) {
      System.out.println(s);
    }

    // 读取标准错误
    System.out.println("标准错误:");
    while ((s = stdError.readLine()) != null) {
      System.out.println(s);
    }
  }

}
